package com.su.dingtalk.controller;

import cn.hutool.json.JSONUtil;
import com.su.dingtalk.model.DingTalkLoginAuthCallbackReqDTO;
import com.su.dingtalk.service.IDingTalkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/dingtalk")
public class DingTalkController {

    @Resource
    private IDingTalkService dingTalkService;


    /**
     * 请求登录
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/authorize")
    public void authorizeUrl(HttpServletResponse response) throws IOException {
        log.info("进入授权请求");
        String url = dingTalkService.genAuthorize();
        log.info("生成的url:" + url);
        // 重定向，当然也可以将改地址返回给前端，让其将二维码内嵌到页面中，适配网站设计
        response.sendRedirect("https://login.dingtalk.com/oauth2/auth?" + url);
    }


    /**
     * 登录回调
     *
     * @param source
     * @param req
     * @return
     */
    @RequestMapping("/callback/{source}")
    public String callback(@PathVariable String source, DingTalkLoginAuthCallbackReqDTO req) {
        log.info("source" + source);
        log.info("req" + JSONUtil.toJsonStr(req));
        String callback = null;
        try {
            callback = dingTalkService.callback(source, req);
            log.info("callback" + JSONUtil.toJsonStr(callback));
        } catch (Exception e) {
            log.error("获取 accesstoken 失败", e);
            log.error("获取用户通讯录个人信息 失败", e);
        }
        return callback;
    }


}
